<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="(e) => {
          (searchlist = { ...e }), (currentPage = 1), getTableDataList();
        }
        ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :tableThead="tableThead" :dataList="dataList">
        <template v-slot:returnQuantity="{ row }">
          <span>{{ row.num }}{{ row.castUnit.symbol }}</span>
        </template>
        <template v-slot:materialName="{ row }">
          {{ row.material.materialName }}
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="changePageSize" :size="pageSize"  @current-change="handleCurrentChange" :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false" :title="titleText" :visible.sync="dialogFormVisible">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-form-item label="发货单编号:" :prop="'arriveOrderNo'" :rules="{
            required: true,
            message: '发货单编号不能为空',
            trigger: 'change',
          }" class="w50p">
            <el-select v-model="formData.arriveOrderNo" placeholder="选择发货单编号" filterable clearable class="w100p"
              @change="queryOnHandQuantity">
              <el-option v-for="item in arrivalList" :key="item.deliveryNo" :label="item.saleOrderNo"
                :value="item.deliveryNo" />
            </el-select>
          </el-form-item>
          <el-form-item label="点击选择:" :prop="'materialObj'" :rules="{
            required: true,
            message: '不能为空',
            trigger: 'change',
          }" class="w50p">
            <el-select v-model="formData.materialObj" placeholder="点击选择" filterable clearable class="w100p"
              value-key="materialNo" @change="batchObjChange">
              <el-option v-for="item in arrivalDetailList" :key="item.materialNo" :label="item.materialName"
                :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="	退货方式" class="w50p">
            <el-select v-model="formData.returnMethod" placeholder="选择退货方式" filterable clearable class="w100p">
              <el-option :label="'退款'" :value="'退款'" />
              <el-option :label="'换货'" :value="'换货'" />
              <el-option :label="'退货'" :value="'退货'" />
            </el-select>
          </el-form-item>
          <el-form-item label="换算率" class="w50p" prop="vchangerate" :rules="[
            {
              required: false,
              pattern: /^[+]?(\d+)$|^[+]?(\d+\.\d+)$/,
              message: '值为大于0的数',
              trigger: ['change', 'blur'],
            },
          ]">
            <el-input v-model="formData.vchangerate" disabled />
          </el-form-item>
          <el-form-item label="退货金额" class="w50p" prop="returnAmount" :rules="[
            {
              required: false,
              pattern: /^[+]?(\d+)$|^[+]?(\d+\.\d+)$/,
              message: '值为大于0的数',
              trigger: ['change', 'blur'],
            },
          ]">
            <el-input v-model="formData.returnAmount" clearable />
          </el-form-item>
          <div class="w50p">
            <el-form-item style="width: 100%" prop="returnQuantity" label="退货数量" :rules="[
              {
                required: false,
                pattern: /^[+]?(\d+)$|^[+]?(\d+\.\d+)$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
            ]">
              <el-input v-model="formData.returnQuantity" clearable />
              <el-input v-model="formData.castUnitSymbol" disabled />
            </el-form-item>
          </div>
          <div class="w50p">
            <el-form-item label="数量" style="width: 100%">
              <el-input v-model="formData.num" disabled />
              <el-input v-model="formData.unitSymbol" disabled />
            </el-form-item>
          </div>
          <el-form-item label="退货人:" :prop="'returnPersonName'" :rules="{
            required: true,
            message: '退货人不能为空',
            trigger: 'change',
          }" class="w50p">
            <el-select v-model="formData.returnPersonName" placeholder="选择退货人" filterable clearable class="w100p">
              <el-option v-for="item in personList" :key="item.value" :label="item.person.name"
                :value="item.person.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="退货原因" class="w50p">
            <el-input v-model="formData.reason" placeholder="请输入退货原因" clearable />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";

import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage";
import purchaseApi from "@/api/livestock-manage/purchaseManage/purchase-return-record";
import arrivalApi from "@/api/livestock-manage/sale-manage/delivery";
import arrivaldetailApi from "@/api/livestock-manage/sale-manage/delivery-detail";
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage";

export default {
  name: "SheepInformation",
  components: { SearchForm, TableData, BtnSlot, Pagination, MainSlot },
  mixins: [mymixin],
  data() {
    return {
      formItemList: [
        {
          label: "销售订单编号",
          type: "input",
          param: "orderNo",
          isShow: true,
        },
        {
          selectOptions: [
            { text: "退款", value: "退款" },
            { text: "换货", value: "换货" },
          ],
          label: "退货方式",
          type: "select",
          param: "returnMethod",
          multiple: false,
          isShow: true,
        },
        {
          label: "退货人",
          param: "returnPersonName",
          selectOptions: [],
          isShow: true,
          multiple: false,
          type: "select",
        },
        {
          label: "退货产品",
          param: "materialNo",
          selectOptions: [],
          isShow: true,
          multiple: false,
          type: "select",
        },
      ], //搜索
      selectionList: [],
      tableThead: [],
      btnList: ["add"],
      selectIndex: 0,
      total: 100,
      currentPage: 1,
      dataList: [],
      SupplierList: [],
      personList: [],
      materialList: [],
      // ===================================下面可能是用不上的，但是不敢删
      tableColumn: [],
      searchlist: {},
      formConfig: [
        {
          type: "select",
          prop: "returnMethod",
          label: "退货方式",
          options: [
            { name: "退款", value: "退款" },
            { name: "换货", value: "换货" },
            { name: "退货", value: "退货" },
          ],
          optionKey: { label: "name", value: "value" },
        },
        {
          type: "select",
          prop: "returnPersonName",
          label: "退货人",
          options: [],
          optionKey: { label: "name", value: "value" },
        },
        {
          label: "销售订单编号",
          prop: "orderNo",
          type: "input",
        },
        {
          label: "退货产品",
          prop: "materialNo",
          type: "select",
          options: [],
          optionKey: { label: "materialName", value: "materialNo" },
        },
      ],
      selectedStaffList: [],
      // selectValue 用于传递select的编号
      formDatalists: [
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "returnMethod",
          selectValue: "",
          typeObj: {
            list: [
              { name: "退款", value: "退款" },
              { name: "换货", value: "换货" },
              { name: "退货", value: "退货" },
            ],
          },
          name: "退货方式",
          required: true,
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "returnPersonName",
          selectValue: "returnPersonName",
          typeObj: {},
          name: "退货人",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "orderNo",
          selectValue: "",
          typeObj: {},
          name: "销售订单编号",
          required: true,
          notSearch: true,
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "materialName",
          porpObj: "material",
          porpName: "materialName",
          selectValue: "materialNo",
          typeObj: {},
          name: "产品",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "returnQuantity",
          porpObj: "castUnit",
          porpName: "num",
          selectValue: "",
          typeObj: {},
          name: "数量",
          required: false,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "vchangerate",
          selectValue: "",
          typeObj: {},
          name: "换算率",
          required: false,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "returnAmount",
          selectValue: "",
          typeObj: {},
          name: "退货金额",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "reason",
          selectValue: "",
          typeObj: {},
          name: "退货原因",
          required: false,
          notSearch: true,
        },
      ],
      arrivalList: [],
      arrivalDetailList: [],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.vchangerate && val.returnQuantity) {
          this.$set(
            val,
            "num",
            isNaN(val.vchangerate * val.returnQuantity)
              ? ""
              : val.vchangerate * val.returnQuantity
          );
        }
      },
    },
  },
  created() {
    let list = [];
    this.formDatalists.forEach((el) => {
      let obj = {
        isShow: true,
        label: el.name,
      };
      if (el.prop == "returnQuantity" || el.prop == "materialName") {
        obj.slotName = el.prop;
      } else {
        obj.prop = el.prop;
      }
      list.push(obj);
    });
    this.tableThead = list;
    this.search();
    this.getPerson();
    this.arrival();
    this.getMaterialList();
  },
  methods: {
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = [];
      list.forEach((item, index) => {
        if (item.param == "supplierNo") {
          let selectOptions = this.SupplierList.map((data) => {
            return {
              text: data.supplierName,
              value: data.supplierNo,
            };
          });
          item.selectOptions = selectOptions;
        }
        if (item.param == "returnPersonName") {
          let selectOptions = this.personList.map((data) => {
            return {
              text: data.person.name,
              value: data.person.name,
            };
          });
          item.selectOptions = selectOptions;
        }
        if (item.param == "materialNo") {
          let selectOptions = this.materialList.map((data) => {
            return {
              text: data.materialName,
              value: data.materialNo,
            };
          });
          item.selectOptions = selectOptions;
        }
      });
      this.$nextTick(() => {
        this.$set(this, "formItemList", list);
      });
      console.log(this.formItemList);
    },

    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.add();
      } else if (flag == "delete") {
        if (this.selectionList.length > 0) {
          this.handleDelete(this.selectionList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
    },
    getMaterialList() {
      materialApi.getqueryList({}).then((res) => {
        if (res.code === 1) {
          this.materialList = res.data;
          this.setFormOptions()
          this.$set(this.formDatalists[3], "typeObj", {
            list: res.data,
            listName: ["materialName", "materialNo"],
          });
          this.setOptions(this.formConfig, "materialNo", res.data);
        }
      });
    },
    // 获取记录人列表
    getPerson() {
      personApi.getStaffListByCondition().then((res) => {
        if (res.code === 1) {
          let list = [];
          this.personList = res.data || [];
          this.setFormOptions()
          res.data.forEach((item) => {
            list.push({
              name: item.person.name,
              value: item.person.name,
            });
          });
          this.setOptions(this.formConfig, "returnPersonName", list);
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "returnPersonName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    arrival() {
      arrivalApi.conditionQuery({}).then((res) => {
        this.arrivalList = res.data;
      });
    },
    async queryOnHandQuantity(e) {
      if (e) {
        const { data: res } = await arrivaldetailApi.queryListByDeliveryNo(e);
        this.arrivalDetailList = res;
      } else if (e) {
        this.$message.warning("请重新选择物料");
      }
    },
    batchObjChange(e) {
      // this.$set()
      let formData = { ...this.formData };
      this.$set(formData, "vchangerate", e.exchangeRate);
      if (e.deliveryDetailNo) {
        this.$set(formData, "orderDetailNo", e.deliveryDetailNo);
      }
      if (e.deliveryNo) {
        this.$set(formData, "orderNo", e.deliveryNo);
      }
      if (e.totalPrice) {
        this.$set(formData, "returnAmount", e.totalPrice);
      }
      if (e.confirmQuantity) {
        this.$set(formData, "returnQuantity", e.confirmQuantity);
      }
      this.formData = { ...formData, ...e };
      // console.log(e);
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          returnRecordType: "销售",
          ...this.searchlist,
        },
      };
      purchaseApi.pageQuery(params).then((res) => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          // 赋值总条数
          this.total = data.totalElements;
          // 赋值数组
          this.dataList = data.content || [];
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.returnRecordNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      purchaseApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          purchaseApi.numberDel(val).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => { });
    },
    add() {
      this.formData = {
        returnRecordType: "销售",
      };
      this.nowChanceStau = "add";
      this.titleText = "添加退货记录";
      this.addActive = true;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      let index = this.arrivalList.findIndex((el) => {
        return el.deliveryNo === row.orderNo;
      });
      this.queryOnHandQuantity(this.arrivalList[index].deliveryNo);
      this.formData = {
        ...row,
        arriveOrderNo: this.arrivalList[index].deliveryNo,
        materialObj: row.material,
      };
      this.nowChanceStau = "edit";
      this.titleText = "修改退货记录";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    save(formData) {
      console.log(this.formData);
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let formData = { ...this.formData };
            purchaseApi.edit(formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let person = { ...this.formData };
            purchaseApi.add(person).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-dialog__wrapper .el-dialog .el-form-item .el-form-item__label {
  min-width: 140px;
}

::v-deep .el-form-item[data-v-3d395f82] {
  display: flex;
  margin-bottom: 10px;
  margin-right: 20px;
}

::v-deep .el-dialog__body {
  max-height: 66vh;
  overflow-y: auto;
}

::v-deep .el-form {
  display: flex;
  flex-wrap: wrap;

  .el-form-item__content {
    display: flex;
    margin-right: 20px;
  }
}

.xunhuan {
  margin-bottom: 50px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .goods {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: left;
    padding-left: 140px;
  }

  .editBox {
    z-index: 100;
    position: absolute;
    right: 0px;
    bottom: -30px;
  }
}

.zhu {
  display: flex;

  ::v-deep .el-input__inner {
    background-color: rgb(241, 239, 239) !important;
  }
}

.numberUnit {
  display: flex;

  .one {
    width: 75%;
  }

  .two {
    width: 25%;
  }
}
</style>
